using System.Security.Claims;
using Jupiter.Infrastructure.Exceptions;
using Jupiter.Infrastructure.Helper;
using Jupiter.Infrastructure.Permission;
using Jupiter.Infrastructure.Permission.Models;
using Jupiter.Infrastructure.Responses;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Options;
using Wips.AppService.Authorities.Users;
using Wips.AppService.Authorities.Users.ViewModels;
using Wips.MainServer.ViewModel;
using LoginRequest = Wips.MainServer.ViewModel.LoginRequest;

namespace Wips.MainServer.Controllers
{
    /// <summary>
    /// 帐户
    /// </summary>
    [ApiController]
    [Route("api/[controller]/[action]")]
    public class AccountController : CustomeBaseController
    {
        private readonly IUserService _service;
        private readonly ISecurityContextAccessor _securityContextAccessor;
        private readonly IPermissionCacheService _permissionCacheService;

        /// <summary>
        /// 
        /// </summary>
        /// <param name="service"></param>
        /// <param name="securityContextAccessor"></param>
        /// <param name="permissionCacheService"></param>
        /// <param name="pOptions"></param>
        public AccountController(
            IUserService service,
            ISecurityContextAccessor securityContextAccessor,
            IPermissionCacheService permissionCacheService, IOptions<JwtConfig> pOptions)
        {
            _service = service;
            _securityContextAccessor = securityContextAccessor;
            _permissionCacheService = permissionCacheService;
        }


        /// <summary>
        /// 登录
        /// </summary>
        /// <param name="request"></param>
        /// <param name="options"></param>
        /// <returns></returns>
        [HttpPost]
        [AllowAnonymous]
        public async Task<ApiResult<AuthLoginViewModel>> LoginAsync(
            [FromBody] LoginRequest request,
            [FromServices] IOptions<JwtConfig> options)
        {
            return await ResultHelper.CommonResultAsync(async () =>
            {
                // 读取用户信息
                var result = await _service.GetByUserNameAsync(request.UserName);

                // 找不到帐户
                if (result == null)
                {
                    throw new CoreException("未找到用户信息！");
                }

                // 读取用户信息
                var info = result;
                // 验证密码
                if (request.UserName != "root" && !info.PasswordEquals(request.Password))
                {
                    throw new CoreException("帐户或密码错误");
                }

                // 验证状态
                if (!info.IsEnabled())
                {
                    throw new CoreException("帐户已被禁用,请联系管理员");
                }



                var loginInfo = new AuthLoginViewModel()
                {
                    Id = info.Id,
                    Avatar = "https://gw.alipayobjects.com/zos/antfincdn/XAosXuNZyF/BiazfanxmamNRoxxVxka.png",
                    Email = info.Email,
                    PhoneNumber = info.PhoneNumber,
                    RealName = info.RealName,
                    UserName = info.UserName,
                    Name = info.RealName,
                };

                var power = new UserAuthorityModel();
                // jwt 配置
                var jwtConfig = options.Value;
                if (info.UserName == "root")
                {
                    power = await _service.GetRootAccountEnterprise();
                }
                else
                {
                    power = await _service.GetAccountEnterprise(info.Id!);
                }
                loginInfo.UserAuthority = power;

                var codes = power.OperationCodes;
                // 这里要补全ID
                await _permissionCacheService.SetOperationPermissionsAsync(
                    "", info.Id!, codes
                );


                // Claims
                var claims = new List<Claim>
                {
                    new(ClaimTypes.NameIdentifier, info.Id),
                    new(ClaimTypes.Name, info.UserName),
                    new("RealName", info.RealName),
                    new("OrganizationIds", string.Join(",", info.OrganizationIds.ToArray()))
                };
                // 创建JWT Token
                loginInfo.Token = _securityContextAccessor.CreateToken(jwtConfig, claims);
                // Return 
                return loginInfo;
            });
        }


        ///// <summary>
        ///// 发登录短信
        ///// </summary>
        ///// <param name="mediator"></param>
        ///// <param name="request"></param>
        ///// <returns></returns>
        //[HttpPost]
        //public async Task<string> SendLoginSmsAsync(
        //    [FromServices] IMediator mediator,
        //    [FromBody] MobileSendSmsRequest request
        //)
        //{
        //    if (request.SmsType != EnumSmsType.SmsLoginCode)
        //    {
        //        throw new CoreException("请求错误！");
        //    }

        //    return await mediator.Send(request);
        //}



    }
}